# --- 初始化 ---
import logging
import time
from flask import Flask

import api.web.rule_config_controller
import api.web.rule_trigger_controller
import api.web.similar_index_controller
import api.web.health_controller
from api.contexts.wrapper import RecyclableContextVar
from configs import web_config

app = Flask(__name__)
app.register_blueprint(api.web.rule_config_controller.app, url_prefix='/api/v1')
app.register_blueprint(api.web.rule_trigger_controller.app, url_prefix='/api/v1')
#import api.web.duplicates_controller
# app.register_blueprint(api.web.duplicates_controller.app, url_prefix='/api/v1')
app.register_blueprint(api.web.similar_index_controller.app, url_prefix='/api/v1')
app.register_blueprint(api.web.health_controller.app, url_prefix='/api/v1')
logger = logging.getLogger(__name__)


# add before request hook
@app.before_request
def before_request():
    # add an unique identifier to each request
    RecyclableContextVar.increment_thread_recycles()


def initialize_extensions(app: Flask):
    app.config.from_mapping(web_config.model_dump())

    from extensions import (
        ext_database,
        ext_logging,
        ext_load,
    )

    extensions = [
        ext_logging,
        ext_database,
        ext_load,
    ]

    for ext in extensions:
        short_name = ext.__name__.split(".")[-1]
        start_time = time.perf_counter()
        ext.init_app(app)
        end_time = time.perf_counter()
        if web_config.DEBUG:
            logger.info(f"Loaded {short_name} ({round((end_time - start_time) * 1000, 2)} ms)")


initialize_extensions(app)


def main():
    from gunicorn.app.wsgiapp import WSGIApplication

    # 创建 Gunicorn 应用实例
    gunicorn_app = WSGIApplication()

    # 可以通过配置或直接设置参数
    gunicorn_app.cfg.set('bind', '0.0.0.0:5000')
    gunicorn_app.cfg.set('workers', 2)
    gunicorn_app.cfg.set('threads', 4)
    gunicorn_app.cfg.set('worker_class', 'gthread')  # 启用多线程 worker
    gunicorn_app.app_uri = 'app:app'  # 模块名:应用实例名

    # 运行应用
    gunicorn_app.run()


if __name__ == "__main__":
    # app.run(debug=False,host="0.0.0.0", port=5000)
    from waitress import serve

    serve(app, host="0.0.0.0", port=5000, threads=8)
